package com.huodongrili.calender.widget;

import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.DecelerateInterpolator;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.ListView;
import android.widget.Scroller;

public class EventListView extends ListView implements OnScrollListener {

	private float mLastY = -1; // save event y

	private EventListFooter mFooterView;

	private int mTotalItemCount;

	private final float OFFSET_RADIO = 1.8f; // support iOS like pull
	// feature.

	private final int PULL_LOAD_MORE_DELTA = 50; // when pull up >= 50px
	// at bottom, trigger
	// load more.
	private Scroller mScroller; // used for scroll back

	private boolean mEnablePullLoad;
	private boolean mPullLoading;

	// for mScroller, scroll back from header or footer.
	private int mScrollBack;
	private final int SCROLLBACK_FOOTER = 1;

	private final int SCROLL_DURATION = 400; // scroll back duration

	private LoadMoreListener mLoadListener;
	private OnScrollListener mScrollListener; // user's scroll listener

	public EventListView(Context context, AttributeSet attrs) {
		super(context, attrs);

		super.setOnScrollListener(this);

		mScroller = new Scroller(context, new DecelerateInterpolator());

		mFooterView = new EventListFooter(context);
		addFooterView(mFooterView);
	}

	@Override
	public void setOnScrollListener(OnScrollListener l) {
		mScrollListener = l;
	}

	@Override
	public void onScroll(AbsListView view, int firstVisibleItem,
			int visibleItemCount, int totalItemCount) {

		mTotalItemCount = totalItemCount;
		if (mScrollListener != null) {
			mScrollListener.onScroll(view, firstVisibleItem, visibleItemCount,
					totalItemCount);
		}

	}

	@Override
	public void onScrollStateChanged(AbsListView view, int scrollState) {
		if (mScrollListener != null) {
			mScrollListener.onScrollStateChanged(view, scrollState);
		}

	}

	public void setLoadMoreListener(LoadMoreListener l) {
		mLoadListener = l;
	}

	public void setFooterVisible(int visibility) {
		mFooterView.setVisibility(visibility);
	}

	@Override
	public boolean onTouchEvent(MotionEvent ev) {

		if (mFooterView.getVisibility() == GONE) {
			return super.onTouchEvent(ev);
		}

		if (mLastY == -1) {
			mLastY = ev.getRawY();
		}

		switch (ev.getAction()) {
		case MotionEvent.ACTION_DOWN:
			mLastY = ev.getRawY();
			break;
		case MotionEvent.ACTION_MOVE:
			final float deltaY = ev.getRawY() - mLastY;
			mLastY = ev.getRawY();
			if (getLastVisiblePosition() == mTotalItemCount - 1
					&& (mFooterView.getBottomMargin() > 0 || deltaY < 0)) {
				// last item, already pulled up or want to pull up.
				updateFooterHeight(-deltaY / OFFSET_RADIO);
			}
			break;
		default:
			mLastY = -1; // reset
			if (getLastVisiblePosition() == mTotalItemCount - 1) {
				// invoke load more.
				if (mEnablePullLoad
						&& mFooterView.getBottomMargin() > PULL_LOAD_MORE_DELTA) {
					startLoadMore();
				}
				resetFooterHeight();
			}
			break;
		}
		return super.onTouchEvent(ev);
	}

	@Override
	public void computeScroll() {
		if (mScroller.computeScrollOffset()) {

			mFooterView.setBottomMargin(mScroller.getCurrY());
			postInvalidate();
			invokeOnScrolling();
		}
		super.computeScroll();
	}

	private void invokeOnScrolling() {
		if (mScrollListener instanceof OnXScrollListener) {
			OnXScrollListener l = (OnXScrollListener) mScrollListener;
			l.onXScrolling(this);
		}
	}

	public void setPullLoadEnable(boolean enable) {
		mEnablePullLoad = enable;
		if (!mEnablePullLoad) {
			mFooterView.hide();
			mFooterView.setOnClickListener(null);
		} else {
			mPullLoading = false;
			mFooterView.show();
			mFooterView.setState(EventListFooter.STATE_NORMAL);
			// both "pull up" and "click" will invoke load more.
			mFooterView.setOnClickListener(new OnClickListener() {
				@Override
				public void onClick(View v) {
					startLoadMore();
				}
			});
		}
	}

	/**
	 * stop load more, reset footer view.
	 */
	public void stopLoadMore() {
		if (mPullLoading == true) {
			mPullLoading = false;
			mFooterView.setState(EventListFooter.STATE_NORMAL);
		}
	}

	private void updateFooterHeight(float delta) {
		int height = mFooterView.getBottomMargin() + (int) delta;
		if (mEnablePullLoad && !mPullLoading) {
			if (height > PULL_LOAD_MORE_DELTA) { // height enough to invoke load
													// more.
				mFooterView.setState(EventListFooter.STATE_READY);
			} else {
				mFooterView.setState(EventListFooter.STATE_NORMAL);
			}
		}
		mFooterView.setBottomMargin(height);

		// setSelection(mTotalItemCount - 1); // scroll to bottom
	}

	private void resetFooterHeight() {
		int bottomMargin = mFooterView.getBottomMargin();
		if (bottomMargin > 0) {
			mScrollBack = SCROLLBACK_FOOTER;
			mScroller.startScroll(0, bottomMargin, 0, -bottomMargin,
					SCROLL_DURATION);
			invalidate();
		}
	}

	private void startLoadMore() {
		mPullLoading = true;
		mFooterView.setState(EventListFooter.STATE_LOADING);
		if (mLoadListener != null) {
			mLoadListener.onLoadMore();
		}
	}

	/**
	 * implements this interface to get refresh/load more event.
	 */
	public interface LoadMoreListener {
		public void onLoadMore();
	}

	/**
	 * you can listen ListView.OnScrollListener or this one. it will invoke
	 * onXScrolling when header/footer scroll back.
	 */
	public interface OnXScrollListener extends OnScrollListener {
		public void onXScrolling(View view);
	}

}
